package cn.imvc.app.models;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.domains.FundFlowType;
import cn.imvc.app.domains.OrderState;
import cn.imvc.app.entities.GoodsOrder;
import cn.imvc.app.entities.SalesReturn;
import cn.imvc.app.entities.StorageOrder;
import cn.imvc.app.entities.User;
import cn.imvc.app.repositories.SalesReturnRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
import cn.imvc.service.api.GoodsService;

@Service
public class SalesReturnModelImpl implements SalesReturnModel{

	@Autowired
	SalesReturnRepository salesReturnRepository;
	@Autowired
	AccountModel accountModel;
	@Autowired
	UserModel userModel;
	@Autowired
	GoodsService goodsService; 			//dubbo公共接口
	@Autowired
	GoodsOrderModel goodsOrderModel;
	@Autowired
	OrdersModel ordersModel;
	
	public Page<SalesReturn> find(ViewRequest viewRequest) {
		return salesReturnRepository.findAll("s","SalesReturn s",ModelUtil.OrderByIdDesc(viewRequest));
	}

	public SalesReturn get(int id) {
		return salesReturnRepository.getOne(id);
	}

	public SalesReturn save(SalesReturn salesReturn) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public SalesReturn update(SalesReturn salesReturn) {
		salesReturn.setUpdatedAt(new Timestamp(new Date().getTime()));
		return salesReturnRepository.saveAndFlush(salesReturn);
	}

	/**
	 * 通过退换货申请
	 */
	public SalesReturn updatePass(SalesReturn salesReturn){
		SalesReturn salesReturnTmp = get(salesReturn.getId());
		if(salesReturnTmp.getState() != (byte)0){
			return null;
		}
		if(salesReturnTmp.getOrder().getRefundAmount()+salesReturn.getRefundAmount()>salesReturnTmp.getOrder().getResultAmount()){
			return null;
		}
		//1、修改退换货申请状态
		BeanUtils.copyProperties(salesReturnTmp, salesReturn,
				new String[] { "id", "refundAmount","state","remark"});
		salesReturn.setUserId(userModel.getSessionUser().getId());
		salesReturn.setState((byte)1);
		salesReturn = update(salesReturn);
		//遍历
		String returnDetail = salesReturn.getReturnDetail();
		String[] returnDetailArray = returnDetail.split(",");
		for(String returnTmp:returnDetailArray){
			String[] detailTmpArray = returnTmp.split(":");
			GoodsOrder goodsOrderTmp = goodsOrderModel.get(Integer.valueOf(detailTmpArray[0]));
			
			//3、更新三级订单状态
			goodsOrderTmp.setState(OrderState.Pass.getValue());
			goodsOrderModel.update(goodsOrderTmp);
		}
		return salesReturn;
	}
	
	/**
	 * 拒绝退换货申请
	 */
	public SalesReturn updateReject(SalesReturn salesReturn){
		SalesReturn salesReturnTmp = get(salesReturn.getId());
		if(salesReturnTmp.getState() != (byte)0){
			return null;
		}
		//1、修改退换货申请状态
		BeanUtils.copyProperties(salesReturnTmp, salesReturn,
				new String[] { "id", "refundAmount","state","remark"});
		salesReturn.setUserId(userModel.getSessionUser().getId());
		salesReturn.setState((byte)2);
		salesReturn.setRefundAmount(0);
		salesReturn = update(salesReturn);
		//遍历
		String returnDetail = salesReturn.getReturnDetail();
		String[] returnDetailArray = returnDetail.split(",");
		for(String returnTmp:returnDetailArray){
			String[] detailTmpArray = returnTmp.split(":");
			GoodsOrder goodsOrderTmp = goodsOrderModel.get(Integer.valueOf(detailTmpArray[0]));
			
			//3、更新三级订单状态
			goodsOrderTmp.setState(OrderState.Reject.getValue());
			goodsOrderModel.update(goodsOrderTmp);
		}
		return salesReturn;
	}
	
	/**
	 * 退换货成功
	 * 操作详情：
	 * 1、修改退换货申请状态
	 * 2、修改一级订货单退款金额
	 * 3、修改三级商品订单状态
	 * 4、返还库存
	 * 5、退还货款
	 * @author changxy
	 */
	public SalesReturn updateSuccess(SalesReturn salesReturn) {
		List<Integer[]> skuInfos = new ArrayList<Integer[]>();
		SalesReturn salesReturnTmp = get(salesReturn.getId());
		if(salesReturnTmp.getState() != (byte)1){
			return null;
		}
		//1、修改退换货申请状态
//		BeanUtils.copyProperties(salesReturnTmp, salesReturn,
//				new String[] { "id", "refundAmount","state","remark"});
//		salesReturn.setUserId(userModel.getSessionUser().getId());
//		salesReturn.setRefundAmount(salesReturn.getRefundAmount());
//		int preRefundAmount = salesReturnTmp.getOrder().getRefundAmount() == null 
		Integer refundAmount = salesReturnTmp.getOrder().getRefundAmount()+salesReturnTmp.getRefundAmount();
		if(refundAmount>salesReturnTmp.getOrder().getResultAmount()){
			return null;
		}
		salesReturnTmp.setState((byte)3);
		salesReturnTmp.setRefundTime(new Date());
		salesReturnTmp = update(salesReturnTmp);
		//2、更新一级订单退款额（累计退款额）
		ordersModel.updateRefundAmount(refundAmount, salesReturnTmp.getOrder().getId());
		//遍历
		String returnDetail = salesReturnTmp.getReturnDetail();
		String[] returnDetailArray = returnDetail.split(",");
		Integer[] skuInfo;
		int returnPoints = 0;
		for(String returnTmp:returnDetailArray){
			skuInfo = new Integer[3];
			String[] detailTmpArray = returnTmp.split(":");
			GoodsOrder goodsOrderTmp = goodsOrderModel.get(Integer.valueOf(detailTmpArray[0]));
			if(goodsOrderTmp.getPoints() < 0){
				returnPoints += goodsOrderTmp.getPoints();
			}
			skuInfo[0] = goodsOrderTmp.getGoodsSku().getId();
			skuInfo[1] = -Integer.valueOf(detailTmpArray[1]);
			skuInfo[2] = goodsOrderTmp.getId();
			skuInfos.add(skuInfo);
			
			//3、更新三级订单状态
			goodsOrderTmp.setState(OrderState.RefundSuccess.getValue());
			goodsOrderModel.update(goodsOrderTmp);
		}
		if(salesReturnTmp.getType() == (byte)1){
			//4、返还库存
			goodsService.retryBatchUpdateGoodsInventory(skuInfos, false);
		}
		//5、退款操作
		accountModel.retryRefundAccount(salesReturnTmp.getMember().getId(), salesReturnTmp.getRefundAmount(), FundFlowType.Refund.getValue(),String.valueOf(salesReturnTmp.getOrder().getCode()));		
		//6、如果存在积分兑换产品，则返还积分
		if(returnPoints < 0){
			accountModel.retrySaveAccount(salesReturnTmp.getMember().getId(), 0,0,-returnPoints);
		}
		
		return salesReturnTmp;
	}

	/**
	 * 退换货失败
	 * 操作流程：
	 * 1、退换货申请状态
	 * 2、将三级订单状态修改为拒绝退款
	 */
	public SalesReturn updateFail(SalesReturn salesReturn) {
		SalesReturn salesReturnTmp = get(salesReturn.getId());
		if(salesReturnTmp.getState() != (byte)1){
			return null;
		}
		//1、修改退换货申请状态
//		BeanUtils.copyProperties(salesReturnTmp, salesReturn,
//				new String[] { "id", "refundAmount","state","remark"});
//		salesReturn.setUserId(userModel.getSessionUser().getId());
//		salesReturn.setRefundAmount(0);
		salesReturnTmp.setState((byte)4);
		salesReturnTmp = update(salesReturnTmp);
		//遍历
		String returnDetail = salesReturnTmp.getReturnDetail();
		String[] returnDetailArray = returnDetail.split(",");
		for(String returnTmp:returnDetailArray){
			String[] detailTmpArray = returnTmp.split(":");
			GoodsOrder goodsOrderTmp = goodsOrderModel.get(Integer.valueOf(detailTmpArray[0]));
			
			//3、更新三级订单状态
			goodsOrderTmp.setState(OrderState.RefundFailed.getValue());
			goodsOrderModel.update(goodsOrderTmp);
		}
		return salesReturnTmp;
	}
	
	
	public void delete(int id) {
		// TODO Auto-generated method stub
		
	}

	public void deleteBatch(int[] ids) {
		// TODO Auto-generated method stub
		
	}

}
